#include "http-server-on-tcp.h"

#include <string>

#include "util/logger/logger.h"
#include "io-context.h"
#include "http-session-on-tcp.h"


static const char *name() {
    return "HttpServer ";
}


HttpServer::HttpServer(IOContext &context, uint16_t port, HttpDispatcher &dispatcher)
    : acceptor_(context.provider(), tcp::endpoint(tcp::v4(), port), true)
    , dispatcher_(dispatcher) {

    LOGI << name() << "constructed, port: " << port;

    
}

HttpServer::~HttpServer() {
    LOGI << name() << "destructed";

}

void HttpServer::remove(HttpSession *ptr) {
    LOGD << name() << "remove component: " << ptr;
    connections_.erase(ptr);
}

void HttpServer::start()
{
    asyncAccept();
}

void HttpServer::asyncAccept() {
    acceptor_.async_accept([this](std::error_code err, tcp::socket socket) {
        LOGD << name() << "accepted new connection from "
            << socket.remote_endpoint().address() << ":" << socket.remote_endpoint().port();

        if (err) {
            LOGE << name() << "accept error: " << err.message();
            return;
        }

        std::unique_ptr<HttpSession> newSession = createSession(std::move(socket));
        HttpSession *newSessionPtr = newSession.get();
        connections_[newSessionPtr] = std::move(newSession);

        asyncAccept();
    });
}
